package com.spyx.product.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.spyx.product.service.FileUploadService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.bucketname}")
    private String bucketName;

    @Value("${aliyun.keyid}")
    private String keyid;

    @Value("${aliyun.keysecret}")
    private String secret;

    @Override
    public String uploadimage(MultipartFile file) {
        //将上传的文件保存到oss中
        // 设置文件名
        String objectName = file.getOriginalFilename();
        //使用uuid生成一个永不重复的字符串
        String s = UUID.randomUUID().toString().replace("-", "");// xsadasd-dfadsa3232sd-dsadas-dasdas
        objectName=s+objectName;
        //重构文件名
        String datapth = new DateTime().toString("yyyy/MM/dd");
        objectName=datapth+"/"+objectName;  // 2024/5/16/32eqeqe32a.jpg

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint,keyid,secret);
        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。  PutObjectRequest(bucket名字, 文件名, 输入流对象);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            ossClient.shutdown();
            System.out.println(result);
            System.out.println(result.getResponse());
            //查看上传结果:
           // System.out.println("响应的状态码:"+result.getResponse().getStatusCode());
           // System.out.println("响应的错误信息:"+result.getResponse().getErrorResponseAsString());
           // System.out.println("上传后的图片保存的路径:"+result.getResponse().getUri());

            //返回上传后文件的路径
            String filepath="https://"+bucketName+"."+endpoint+"/"+objectName;

            return filepath;
        } catch (Exception e) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            e.printStackTrace();
        }
        return  null;
    }
}
